import {
  Component,
  Injector,
  OnDestroy,
  OnInit,
  ViewChild,
} from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { SimpleTableColumn, SimpleTableComponent } from '@delon/abc';
import { SFSchema } from '@delon/form';
import {
  NzMessageService,
  NzModalService,
  NzNotificationService,
  NzTabChangeEvent,
  UploadFile,
} from 'ng-zorro-antd';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { PopService } from '../../../../service/pop/pop.service';
import { CommService } from '../../../../service/comm/comm.service';
import { ProductService } from '../../../../service/prod/product.service';
import { Constant, ServiceResult } from '@core/constant';
import { EmitterService } from '../../../../service/emit.service';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs/index';

@Component({
  selector: 'pop-pops-list',
  templateUrl: './list.component.html',
})
export class PopPopsListComponent implements OnInit, OnDestroy {
  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private msg: NzMessageService,
    private trans: TranslateService,
    private popService: PopService,
    private injector: Injector,
    private comm: CommService,
    private productService: ProductService,
    private router: Router,
    private emit: EmitterService,
    private modalService: NzModalService,
    private notice: NzNotificationService,
  ) {}

  ngOnInit() {
    this.imgSuffix = this.comm.getGoodsUrl();
    this.uploadUrl = this.productService.uploadUrl();
    this.loadBrands();
    setTimeout(() => {
      this.emit.sendMessage('HIDE_REUSE_TAB');
    }, 100);
  }
  ngOnDestroy() {
    this.emit.sendMessage('SHOW_REUSE_TAB');
  }

  // 查询对象
  q: any = {
    sqp: null,
    sku: null,
    brand: null,
    id: null,
    status: null,
  };
  imgSuffix = '';
  uploadUrl = '';
  brands = [];

  changeTabs(args: NzTabChangeEvent) {
    switch (args.index) {
      case 0:
        this.q.status = null;
        break;
      case 1:
        this.q.status = this.cnt.PopStatusUtil.NORMAL;
        break;
      case 2:
        this.q.status = this.cnt.PopStatusUtil.DISABLED;
        break;
    }
    this.st.load(1, this.q);
  }
  loadBrands() {
    const lang = this.trans.currentLang || this.trans.defaultLang;
    this.brands = [];
    this.comm.getBrand().subscribe(data => {
      const ret: ServiceResult = <ServiceResult>data;
      if (ret.status === 200) {
        for (const row of ret['data']['rows']) {
          this.brands.push({
            text: lang === 'en' ? row.labelEnUs : row.labelDefault,
            value: row.value,
          });
        }
      }
    });
  }
  get cnt(): Constant {
    return this.injector.get(Constant);
  }

  list = this.popService.listPopItems2();
  @ViewChild('st') st: SimpleTableComponent;
  columns: SimpleTableColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    { title: 'SAP物料号', index: 'sap', i18n: 'sap' },
    { title: 'SKU描述', index: 'sku', i18n: 'sku_number' },
    { title: '品牌', index: 'brand', i18n: 'brand' },
    // { title: 'SAP物料名称', index: 'sapDesc', i18n: 'Sap Desc' },
    // { title: '名称', index: 'description', i18n: 'description' },
    { title: '图片', index: 'img', i18n: 'img', render: 'img' },
    { title: 'Qty', index: 'qty', i18n: 'qty' },
    { title: '材料', index: 'material', i18n: 'material' },
    { title: '毛重', index: 'grossWeight', i18n: 'G.W.(Kg)' },
    { title: '净重', index: 'netWeight', i18n: 'N.W.(Kg)' },
    { title: '装箱数', index: 'ctnQty', i18n: 'ctn_qty' },
    // { title: '外箱尺寸', index: 'cm', i18n: 'Box Size' },
    { title: 'EXW', index: 'exw', i18n: 'EXW' },
    { title: 'CIF', index: 'cif', i18n: 'CIF' },
    {
      title: '价格单位',
      index: 'priceUnit',
      i18n: 'price_unit',
      render: 'priceUnit',
      tag: {
        USD: { text: 'USD', color: 'geekblue' },
        EUR: { text: 'EUR', color: 'orange' },
        '': { text: 'NO', color: 'purple' },
        null: { text: 'NO', color: 'purple' },
      },
    },
    {
      title: '状态',
      type: 'badge',
      index: 'status',
      i18n: 'status',
      badge: {
        disabled: { text: '下架', color: 'error' },
        normal: { text: '上架', color: 'success' },
        '': { text: 'null', color: 'default' },
        null: { text: 'null', color: 'default' },
      },
    },
    {
      title: '操作',
      i18n: 'operator',
      buttons: [
        {
          text: '编辑',
          i18n: 'edit',
          type: 'link',
          click: (record: any) =>
            this.router.navigate(['/pop/list/pops/edit/' + record.id]),
        },
      ],
    },
  ];

  back() {
    this.router.navigate(['/pop/list']);
  }
  checkedList = [];

  checkboxChange(list: any[]) {
    this.checkedList = list;
  }

  exportPop() {
    if (this.checkedList.length > 0) {
      this.st.export(this.checkedList, { filename: 'POP单品清单.xlsx' });
    } else {
      let param = `?pageNumber=1&pageSize=0`;
      if (this.st.extraParams.sku) {
        param += '&sku=' + this.st.extraParams.sku;
      }
      if (this.st.extraParams.sap) {
        param += '&sap=' + this.st.extraParams.sap;
      }
      if (this.st.extraParams.brand) {
        param += '&brand=' + this.st.extraParams.brand;
      }
      this.st.export(this.list + param, { filename: 'POP单品清单.xlsx' });
    }
  }
  showUpConfirm() {
    if (this.checkedList.length === 0) {
      this.msg.warning('请选择POP单品');
      return;
    }

    this.modalService.confirm({
      nzTitle: `警告`,
      nzContent: `确定<span class="border-bottom-1 border-error">上架</span>选中的<b style="color: red;"> ${
        this.checkedList.length
      }</b> 项套餐?`,
      nzOkText: '确定',
      nzOkType: 'danger',
      nzOnOk: () => this.batchUp(),
      nzCancelText: '取消',
    });
  }
  showDownConfirm() {
    if (this.checkedList.length === 0) {
      this.msg.warning('请选择POP套餐');
      return;
    }

    this.modalService.confirm({
      nzTitle: `警告`,
      nzContent: `确定<span class="border-bottom-1 border-error">下架</span>选中的<b style="color: red;"> ${
        this.checkedList.length
      }</b> 项套餐?`,
      nzOkText: '确定',
      nzOkType: 'danger',
      nzOnOk: () => this.batchDown(),
      nzCancelText: '取消',
    });
  }

  // 批量上架
  private batchUp() {
    const ids = this.checkedList.map(v => v.id);
    this.popService
      .batchUpPopItems(ids.toString())
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(() => {
        this.st.reload();
        this.checkedList = [];
      });
  }
  // 批量下架
  private batchDown() {
    const ids = this.checkedList.map(v => v.id);
    this.popService
      .batchDownPopItems(ids.toString())
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(() => {
        this.st.reload();
        this.checkedList = [];
      });
  }

  previewImage = '';
  previewVisible = false;

  showImage(src) {
    this.previewImage = src;
    this.previewVisible = true;
  }

  manuallyAddPopItem() {
    setTimeout(() => {
      this.router.navigate(['/pop/list/pops/add']);
    }, 500);
  }
  uploadExcelUrl = this.popService.uploadPops();
  loading = false;

  uploadProd(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
    }
    if (info.file.status === 'done') {
      this.loading = false;
      this.st.load();
      this.notice.create('success', '成功', '商品导入成功');
    }
    if (info.file.status === 'error') {
      this.loading = false;
      this.notice.create('error', '失败', '商品导入失败');
    }
  }
}
